<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: GetCircle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\chat;

use app\api\model\dao\UserAccount;
use app\library\Common;
use app\library\Error;
use app\library\HuanXin;
use app\library\PageBase;

class CheckPhoneBook extends PageBase
{

    public $objUserAccount;

    public function __construct()
    {
        parent::__construct();
        $this->objUserAccount  = new UserAccount();
    }

    /**
     * page 入口
     *
     * @param $param
     * @return array
     */
    public function excute($param)
    {
        $this->checkToken($param);

        $this->user_id = $this->user_id ? $this->user_id : 0;

        if (empty($param['phone_book'])) {
            return $this->getRes(Error::ERR_PARAM);
        }

        $phone_book = json_decode($param['phone_book'], true);

        $arrPhone = [];

        foreach ($phone_book as $val) {
            $arrPhone[] = $val['phone'];
        }

        $user_account = [];

        if (!empty($arrPhone)) {
            $conds = [
                'phone' => ['in', $arrPhone],
                'huanxin_username' => ['<>', '']
            ];
            $user_account = $this->objUserAccount->getUserAccountByConds($conds, ['id', 'phone', 'nick_name', 'avatar', 'huanxin_username']);

            if (empty($user_account)) {
                $user_account = [];
            }
        }

        $this->huanxin_username = Common::encryptString($this->phone);
        $ret = HuanXin::getFriends($this->huanxin_username);
        $friend_username = [];
        if (!empty($ret['data'])) {
            $friend_username = $ret['data'];
        }

        foreach ($user_account as $key => $val) {
            $huanxin_username = Common::encryptString($val['phone']);
            $ret = HuanXin::getUser($huanxin_username);
            if (empty($ret)) {
                unset($user_account[$key]);
                continue;
            }
        }

        $data = [];
        foreach ($user_account as $val) {

            $is_friend = in_array($val['huanxin_username'], $friend_username) ? '1' : '0';

            $data[] = [
                'userid' => $val['id'],
                'phone' => $val['phone'],
                'nick_name' => $val['nick_name'],
                'photo' => $val['avatar'],
                'is_friend' => $is_friend
            ];
        }

        $this->data = $data;

        return $this->getRes();

    }
}
